package org.restly.core;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Oct 23, 2008, 7:08:55 AM
 *
 * @author <a href="http://restly.org/">Erik Beeson</a>
 */
public final class ContentTypes {
	private static List<ContentType> contentTypes = Collections.unmodifiableList(Arrays.asList(
			ContentType.TEXT_XML, ContentType.JSON, ContentType.TEXT_PLAIN
	));

	private ContentTypes() {
	}

	public static void init(ServletContext context) {
		List<ContentType> list = new ArrayList<ContentType>();

		String s = context.getInitParameter(ContentTypes.class.getName());
		if(isNotBlank(s)) {
			for(String type : s.split(",")) {
				type = type.trim();
				list.add(new ContentType(type + ";charset=UTF-8"));
			}
		}

		contentTypes = Collections.unmodifiableList(list);
	}

	public static List<ContentType> getContentTypes() {
		return contentTypes;
	}

	public static ContentType getBestContentType(String acceptHeader) {
		if(isNotBlank(acceptHeader)) {
			return ContentType.getBestContentType(acceptHeader, getContentTypes());
		} else {
			return null;
		}
	}

	public static ContentType getBestContentType(HttpServletRequest request) {
		return getBestContentType(request.getHeader("Accept"));
	}

	private static boolean isNotBlank(String s) {
		return s != null && s.trim().length() > 0;
	}
}
